using System;
using System.Collections.Generic;
using System.Text;

namespace SubSonic
{
    public class Sql2005Generator : ANSISqlGenerator
    {
        public Sql2005Generator(SqlQuery query)
            : base(query) {}

        public override string BuildPagedSelectStatement()
        {
            Select qry = (Select)this.query;

            string sql = "";

            string idColumn = GetSelectColumns()[0];
            string pkType = "";
            string sqlType = "";

            string pagingFormat = PAGING_SQL;

            string select = GenerateCommandLine();
            string columnList = select.Replace("SELECT", "");
            string fromLine = GenerateFromList();
            string joins = GenerateJoins();
            string wheres = GenerateConstraints();
            string orderby = GenerateOrderBy();

            if(orderby.Trim() == string.Empty)
                orderby = SqlFragment.ORDER_BY + idColumn;

            if(qry.Aggregates.Count > 0)
                joins += GenerateGroupBy();

            int pageStart = 0;
            int pageEnd = 0;

            pageStart = qry.CurrentPage * qry.PageSize;
            pageEnd = pageStart + query.PageSize;

            sql = string.Format(pagingFormat, columnList, orderby, fromLine, joins, wheres, pageStart, pageEnd);

            return sql;
        }

        private const string PAGING_SQL =
            @"
SELECT *
FROM     (SELECT ROW_NUMBER() OVER ({1}) AS Row, 
{0} 
{2}
{3}
{4}
)
            AS PagedResults
WHERE  Row >= {5} AND Row < {6}";
    }
}
